import { defineStore } from 'pinia';
import {
  login as userLogin,
  logout as userLogout,
  getUserInfo,
  LoginData,
} from '@/api/user';
import { setToken, clearToken } from '@/utils/auth';
import { removeRouteListener } from '@/utils/route-listener';
import { UserState } from './types';
import useAppStore from '../app';
const useUserStore = defineStore('user', {
  state: (): UserState => ({
    first_name: undefined,
    last_name: undefined,
    avatar: undefined,
    email: undefined,
    gender: undefined,
    is_active: undefined,
    mobile: undefined,
    post: undefined,
    role: undefined,
    dept: undefined,
    id: undefined,
    username:'',
    password:''
  }),

  getters: {
    userInfo(state: UserState): UserState {
      console.log('state',state);
      const info:any = state || JSON.parse(localStorage.getItem('userinfo'))
      return { ...info };
    },
  },

  actions: {
    // switchRoles() {
    //   return new Promise((resolve) => {
    //     this.role = this.role === 'user' ? 'admin' : 'user';
    //     resolve(this.role);
    //   });
    // },
    // Set user's information
    setInfo(partial: Partial<UserState>) {
      this.$patch(partial);
    },
    setLoginInfo(data:any) {
      this.$patch(data);
    },
    // Reset user's information
    resetInfo() {
      
      
      this.$reset();
    },

    // Get user's information
    async info() {
      const res:any = await getUserInfo();
      this.setInfo(res.data);
      localStorage.setItem('userinfo',JSON.stringify(res.data))
    },

    // Login
    async login(loginForm: LoginData) {
      try {
        const res = await userLogin(loginForm);
        setToken(res.data.access);
         this.setLoginInfo(loginForm);
      } catch (err) {
        clearToken();
        throw err;
      }
    },
    logoutCallBack() {
      const appStore = useAppStore();
      this.resetInfo();
      clearToken();
      removeRouteListener();
      appStore.clearServerMenu();
    },
    // Logout
    async logout() {
      this.logoutCallBack();
      // try {
      //   await userLogout();
      // } finally {
      //   this.logoutCallBack();
      // }
    },
  },
});

export default useUserStore;
